package com.library.weidget.wheel.timepicker;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;

import com.jtjrenren.android.taxi.passenger.R;
import com.library.weidget.wheel.scroll.ScrollableView;
import com.library.weidget.wheel.util.TextUtil;
import com.library.weidget.wheel.wheel.WheelView;
import com.library.weidget.wheel.wheel.adapter.ArrayWheelAdapter3;
import com.library.utils.RegexUtils;

import java.util.Date;

import datetime.DateTime;

/**
 * Created by wdl on 2016/2/24.
 */
public class TimePickerCustome extends RelativeLayout {
    private static final int MSG_TIME_PICKED = 0;
    private WheelView mWheelDate;
    private WheelView mWheelHour;
    private WheelView mWheelMinute;
    private ArrayWheelAdapter3 mAdapterDate;
    private ArrayWheelAdapter3 mAdapterHour;
    private ArrayWheelAdapter3 mAdapterMinute;

    private int lastDateValue = -1;
    private boolean dateIsChange = true;


    private DateTime selectDateTime = getCurrentDateTime();

    private TimePickerListener mTimePickerListener;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_TIME_PICKED:
                    if (mTimePickerListener != null) {
                        if (dateIsChange)
                            mTimePickerListener.onPick(selectDateTime);
                        else
                            mTimePickerListener.onPick(null);
                    }
                    break;
            }
        }

        ;
    };

    public TimePickerCustome(Context context) {
        super(context);
        initView(context);
    }

    public TimePickerCustome(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView(context);
    }

    public TimePickerCustome(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView(context);
    }


    public void setDate(Date date) {
        if (date != null) {
            DateTime dateTime = new DateTime(date);
            if (dateTime.isBefore(getCalcDateTime())) {

            } else {
//                selectDateTime = dateTime;
                int c = 0;
                if (isTomorrow(dateTime))
                    c = 1;
                else if (isHt(dateTime))
                    c = 2;
                mWheelDate.setCurrentValue(c);

                String[] hourData = getHourData(dateTime);
                int p = 0;
                for (int i = 0; i < hourData.length; i++) {
                    if (hourData[i].equals(dateTime.getHour() + "点")) {
                        p = i;
                        break;
                    }
                }
                mAdapterHour.setData(hourData);
                mWheelHour.setCurrentValue(p);

                mWheelMinute.setCurrentValue(dateTime.getMinute() / 10 );

                dateIsChange = true;
                mHandler.sendEmptyMessage(MSG_TIME_PICKED);

                onSelcted(null);
            }
        }
    }

    private void initView(Context context) {
        LayoutInflater.from(context).inflate(R.layout.custome_time_picker, this);

        mWheelDate = (WheelView) findViewById(R.id.wheel_view_date);
        mWheelHour = (WheelView) findViewById(R.id.wheel_view_hour);
        mWheelMinute = (WheelView) findViewById(R.id.wheel_view_minute);

        buildAdapters();

        mWheelDate.setAdapter(mAdapterDate);
        mWheelHour.setAdapter(mAdapterHour);
        mWheelMinute.setAdapter(mAdapterMinute);


        ScrollableView.ScrollListener scrollListener = createScrollListener();
        mWheelDate.setScrollListener(scrollListener);
        mWheelHour.setScrollListener(scrollListener);
        mWheelMinute.setScrollListener(scrollListener);

    }

    private ScrollableView.ScrollListener createScrollListener() {
        return new ScrollableView.ScrollListener() {

            @Override
            public void onScrollEnd(View v) {
                onSelcted(v);
            }
        };
    }

    private void onSelcted(View v) {
        //算日期
        int dateCurr = mWheelDate.getCurrentValue();
        int calcDate = dateCurr;
        if (lastDateValue >= 0) {
            calcDate = dateCurr - lastDateValue;
        }
        selectDateTime.addDay(calcDate);
        lastDateValue = dateCurr;

        //算小时
        mAdapterHour.setData(getHourData(selectDateTime));
        String hour = mAdapterHour.getItem(mWheelHour.getCurrentValue());
        if (hour.indexOf("点") > 0) {
            hour = RegexUtils.getNumStr(hour);
            selectDateTime.setHour(Integer.parseInt(hour));
        }

        boolean isNowChoose = false;

        if (selectDateTime.getDay() == getCurrentDateTime().getDay() && "现在".equals(mAdapterHour.getItem(mWheelHour.getCurrentValue()))) {
            mWheelMinute.setStartValue(0);
            mWheelMinute.setCurrentValue(0);
            isNowChoose = true;
        } else {
            if (selectDateTime.getDay() == getCurrentDateTime().getDay() && selectDateTime.getHour() == getCurrentDateTime().getHour()) {
                int mincalc = (getCurrentDateTime().getMinute() + 10) / 10;
                mWheelMinute.setStartValue(mincalc + 1);
            } else
                mWheelMinute.setStartValue(1);

            isNowChoose = false;
        }
        String min = mAdapterMinute.getItem(mAdapterMinute.getValueIndex(mWheelMinute.getCurrentValue()));
        if (min.indexOf("分") > 0) {
            min = RegexUtils.getNumStr(min);
            selectDateTime.setMinute(Integer.parseInt(min));
        }

        if (selectDateTime.isBefore(getCalcDateTime()) || isNowChoose) {
            dateIsChange = false;
        } else {
            dateIsChange = true;
        }

        mHandler.sendEmptyMessage(MSG_TIME_PICKED);
    }


    private void buildAdapters() {
        mAdapterDate = new ArrayWheelAdapter3(TextUtil.getStringArray(getContext(), R.array.time_picker_date_custome));
        mAdapterHour = new ArrayWheelAdapter3(getHourData(selectDateTime));
        mAdapterMinute = new ArrayWheelAdapter3(getMinData());
    }


    /**
     * 获取当前时间
     *
     * @return
     */
    private DateTime getCurrentDateTime() {
        DateTime time = new DateTime();
        return time;
    }

    /**
     * 计算有效显示时间，时间间隔为十分钟
     *
     * @return
     */
    private DateTime getAvailableDateTime() {
        DateTime availableTime = getCurrentDateTime();
        if (availableTime.getMinute() % 10 < 5) {
            availableTime.addMinute(10);
        } else {
            availableTime.addMinute(5);
        }
        int minute = availableTime.getMinute();
        minute = minute / 10 * 10;
        availableTime.setMinute(minute);
        return availableTime;
    }

    private DateTime getCalcDateTime() {
        DateTime avatime = getCurrentDateTime();
        avatime.addMinute(10);
        return avatime;
    }


    private String[] getHourData(DateTime dateTime) {
        String[] datas;

        if (dateTime.getDay() == getCurrentDateTime().getDay()) {
            int currentHour = getCurrentDateTime().getHour();
            DateTime calcDateTime = getCalcDateTime();

            int dd = 24 - currentHour;

            if (calcDateTime.getDay() != getCurrentDateTime().getDay()) {
                dd = 0;
            } else {
                if (calcDateTime.getHour() != getCurrentDateTime().getHour()) {
                    currentHour = calcDateTime.getHour();
                    dd = 24 - currentHour;
                }
            }

            datas = new String[dd + 1];
            datas[0] = "现在";
            for (int i = 0; i < dd; i++) {
                datas[i + 1] = (currentHour + i) + "点";
            }
        } else {
            datas = new String[24];
            for (int i = 0; i < 24; i++) {
                datas[i] = i + "点";
            }
        }
        return datas;
    }

    private String[] getMinData() {
        String[] datas = new String[]{"", "0分", "10分", "20分", "30分", "40分", "50分"};
        return datas;
    }

    private boolean isToday(DateTime time) {
        return getCurrentDateTime().getDay() == time.getDay();
    }

    private boolean isTomorrow(DateTime time) {
        DateTime currentDateTime = getCurrentDateTime();
        currentDateTime.addDay(1);
        return currentDateTime.getDay() == time.getDay();
    }

    private boolean isHt(DateTime time) {
        DateTime currentDateTime = getCurrentDateTime();
        currentDateTime.addDay(2);
        return currentDateTime.getDay() == time.getDay();
    }

    public void setTimePickerListener(TimePickerListener l) {
        this.mTimePickerListener = l;
    }

    public interface TimePickerListener {
        void onPick(DateTime time);
    }
}
